/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package util;

import Facade.AccountFacadeLocal;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

/**
 *
 * @author Admin
 */
public class CheckAccount implements Validator {

    private static final Logger logger = Logger.getLogger("checkAccount");

    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
        try {
            if (lookupAccountFacade().find(value) == null) {
                FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Account does not exist.", "Account does not exist.");
                throw new ValidatorException(message);
            }
        } catch (Exception ex) {
            logger.log(Level.SEVERE, ex.getMessage(), ex);
            FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Persistance error: " + ex.getMessage(), "Persistance error: " + ex.getMessage());
            throw new ValidatorException(message);
        }
    }

    private AccountFacadeLocal lookupAccountFacade() {
        try {
            Context c = new InitialContext();
            return (AccountFacadeLocal) c.lookup("java:comp/env/AccountFacade");
        } catch (NamingException ne) {
            logger.log(Level.SEVERE, "lookupAccountFacade ERROR", ne);
            throw new RuntimeException(ne);
        }
    }
}
